<template>
  <div class="drugStorage">
    <div class="drugStorage-page">
      <div class="drugStorage-page-content">
        <div class="drugStorage-page-form">
          <el-input v-model="mfrName" @change="handlePageChange(1)" @blur="handlePageChange(1)"  style="width:300px" placeholder="药厂名称" :suffix-icon="Search" />
          <div class="drugStorage-page-form-right">
            <el-button type="primary" @click="drugStrorageAdd" v-btnPermission="'btn-mfr-updata'"><el-icon>
                <Plus />
              </el-icon>新建</el-button>
          </div>
        </div>
        <div class="drugStorage-page-table">
          <Table :columns="tableColumns" @selectionChange="selectionChange" :loading="loading"
            :data-source="tableData" />
        </div>
        <div class="drugStorage-page-pagination">
          <Pagination style="margin-left: auto;" :key="pageSize + 'Pagination' + currentPage" :count="total"
            :page-size="pageSize" :pageNo="currentPage" @onPagechange="handlePageChange"
            @onSizechange="handleSizeChange" />
        </div>

      </div>
    </div>
    <Dialog :width="500" :title="title" :radius="12"  :visible="visible" @close="visible = false"
      ref="dialogRef">
      <div class="drugStorage-dialog">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="药厂名称" prop="mfrName">
            <el-input v-model="form.mfrName" placeholder="请输入药厂名称"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" plain @click="close">取消</el-button>
        <el-button type="primary" @click="drugStrorageUpdata" :loading="updataLoading">确定</el-button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Plus } from '@element-plus/icons-vue';
import { ElForm } from 'element-plus';
import type { TableColumn } from '@/types/table';
import type { FormStorage, List } from '@/types/storage/index';
import type { FormInstance, FormRules, Action } from 'element-plus'

import type { MfrTablePagination, MfrInfo, MfrTable } from '@/types/mfr'
import { getMfrList, addMfr, updateMfr, deleteMfr, enableMfr, disableMfr } from '@/api/mfr/index'


const loading = ref<boolean>(false)
const updataLoading = ref<boolean>(false)
const formRef = ref<FormInstance>();
const visible = ref<boolean>(false);
const tableColumns: TableColumn[] = [
  { prop: 'mfrName', label: '药厂名称' },
  { prop: 'isEnabled', label: '状态', type: 'tag' },
  { prop: 'createBy', label: '创建人员' },
  { prop: 'createTime', label: '创建时间' },
  {
    prop: 'action',
    label: '操作',
    type: 'action',
    width: 170,
    componentProps: {
      fixed: 'right',
    },
    buttonGroup: [
      {
        label: '编辑', permissions: 'btn-mfr-edit', type: 'text', click: (row: MfrInfo) => {
          //console.log('编辑', row)
          title.value = '编辑';
          form.value.mfrId = row.mfrId
          form.value.mfrName = row.mfrName
          // 打开弹窗
          visible.value = true;
        }
      },
      {
        label: '启用',permissions: 'btn-mfr-enable', statusName: ['isEnabled'], status: '停用', type: 'text', click: (row: any) => {
          enableMfr(row.mfrId).then((res) => {
            if (res.code == '200') {
              getMfrListApi(); // 刷新列表
              ElMessage({
                type: 'success',
                message: '操作成功',
              });
            } else {
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              // });
            }

          });

        }
      },
      {
        label: '停用', statusName: ['isEnabled'], permissions: 'btn-mfr-disable',status: '启用', type: 'text', color: '#D90000', click: (row: any) => {


          disableMfr(row.mfrId).then((res) => {
            if (res.code == '200') {
              getMfrListApi(); // 刷新列表
              ElMessage({
                type: 'success',
                message: '操作成功',
              });
            } else {
              // ElMessage({
              //   type: 'warning',
              //   message: res.msg,
              // });
            }
          });
        }
      },
      {
        label: '删除', permissions: 'btn-mfr-del', type: 'text', color: '#D90000', click: (row: any) => {
          ElMessageBox.alert('确定要删除吗？', '删除药库', {
            // if you want to disable its autofocus
            // autofocus: false,
            confirmButtonText: '确定',
            callback: (action: Action) => {
               if(action == 'cancel'){
                  return;
              }
              try {
                deleteMfr(row.mfrId).then((res) => {
                  if (res.code == '200') {
                    getMfrListApi(); // 刷新列表
                    ElMessage({
                      type: 'success',
                      message: '操作成功',
                    });
                  } else {
                    // ElMessage({
                    //   type: 'warning',
                    //   message: res.msg,
                    // });
                  }

                });
              } catch (error: any) {
                //console.log(error, '删除失败');

              }

            },
          })

        }
      },

    ]
  }
]

const userinfo = getUserInfo()// 获取用户信息
//表单
const mfrName = ref<string>('')
var form = ref<MfrInfo>({
  mfrName: '',
});

const rules: FormRules = {
  mfrName: [
    { required: true, message: '请输入药厂名称', trigger: 'blur' },
  ]
};

const drugStrorageUpdata = async (): Promise<void> => {
  if (!formRef.value) return;
  // 这里可以添加表单验证逻辑
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      //console.log('表单验证通过');
      if (form.value.mfrId) {
        updataLoading.value = true; // 开始加载
        // 编辑逻辑
        updateMfr(form.value).then((res) => {
          updataLoading.value = false; // 停止加载
          // 关闭弹窗
          if (res.code == '200') {
            visible.value = false; // 关闭弹窗
            ElMessage({
              type: 'success',
              message: '操作成功！',
            });
            getMfrListApi(); // 刷新列表
          } else {
            // ElMessage({
            //   type: 'warning',
            //   message: res.msg,
            // });
          }
        });
      } else {
        // 新增逻辑
        addMfr(form.value).then((res) => {

          if (res.code == '200') {
            visible.value = false; // 关闭弹窗
            ElMessage({
              type: 'success',
              message: '操作成功！',
            });
            getMfrListApi(); // 刷新列表
          } else {
            // ElMessage({
            //   type: 'warning',
            //   message: res.msg,
            // });
          }
          updataLoading.value = false; // 停止加载

        });
      }
      form.value = {
        mfrName: '',
      }; // 重置表单
    } else {
      //console.error('表单验证失败');
      return;
    }
  });
  // await formRef.value.validate();
};

const title = ref<string>('');
const drugStrorageAdd = () => {
  title.value = '新增药库';
  form.value = {
    mfrName: '',
  }; // 重置表单
  visible.value = true;

  //console.log(visible.value, 'visible.value');

};

const selectionChange = (val: any) => {
  //console.log('选中数据:', val);
};

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取药库列表
const tableData = ref<MfrInfo[]>([]);
const getMfrListApi = async () => {
  loading.value = true;
  try {
    const res = await getMfrList({
      mfrName: mfrName.value,
      pageNo: currentPage.value,
      pageSize: pageSize.value,
    });
     if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
    res.data.list.forEach((item: any) => {
      item.isEnabled = item.isEnabled === '1' ? '启用' : '停用';
    });
    tableData.value = res.data.list || [];
    // 更新总条数
    total.value = res.data.totalCount || 0;
  } catch (error) {
    //console.error('请求错误:', error);
  } finally {
    loading.value = false;
  }
};
getMfrListApi();

const close = () => {
  //console.log('关闭弹窗');
  // 重置表单
  form.value = {
    mfrName: '',
  };
  visible.value = false; // 关闭弹窗

};

const handlePageChange = (page: number) => {
  //console.log('当前页:', page);
  currentPage.value = page;
  getMfrListApi(); // 重新获取数据
};
const handleSizeChange = (size: number) => {
  //console.log('每页条数:', size);
  pageSize.value = size;
  currentPage.value = 1; // 重置当前页为1
  getMfrListApi(); // 重新获取数据
};


</script>

<style lang="scss" scoped>
.drugStorage {
  height: 100%;
}

.drugStorage-dialog-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.drugStorage-dialog {
  width: 100%;
  margin: 0 auto;
}

.drugStorage-page {
  background: #fff;
  border-radius: 6px;
  height: 100%;

  .drugStorage-page-nav {
    display: flex;
    align-items: center;
    justify-content: left;
    border-radius: 4px;
    border-bottom: 1px solid #E7E7E7;

    .el-dropdown-link {
      background: rgba(22, 173, 164, 0.08);
      border-radius: 0px 0px 0px 0px;
      padding: 16px 21px;
      cursor: pointer;
      color: var(--el-color-primary) !important;
      display: flex;
      font-size: 16px;
      align-items: center;
    }

  }

  .drugStorage-page-content {
    padding: 10px 24px;
    height: calc(100% - 68px);

    .drugStorage-page-form {
      display: flex;
      align-items: center;

      .drugStorage-page-form-right {
        margin-left: auto;
      }
    }

    .drugStorage-page-table {
      margin-top: 22px;
      height: calc(100% - 64px);
    }

    .drugStorage-page-pagination {
      margin-top: 24px;
      display: flex;
      align-items: center;

    }
  }

}
</style>